const userModel = require('../db/user')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
module.exports = {
    register(req, res) {
        // 接收post数据
        let {username, password, email, tel} = req.body
        console.log(111,username, password);
        // 验证数据是否为空
        if(!username || !password) {
            res.json({
                error_code: 2,
                msg: '数据不允许为空！'
            })
            return
        }
        // 查询是否有这个用户名
        userModel.findOne({username}, (err, docs) => {
            if(err) {
                throw new Error(err)
            }
            if(docs) {
                res.json({
                    error_code: 1,
                    msg: '用户名被占用！'
                })
                return
            }
            userModel.insertMany({
                username,
                password: bcryptjs.hashSync(password, 10),
                email,
                tel
            }, (err, docs) => {
                if(err) {
                    throw new Error(err)
                }
                res.json({
                    error_code: 0,
                    msg: '注册成功！'
                })
            })
        })
    },
    login(req, res) {
        let {username, password} = req.body
        if(!username || !password) {
            res.json({
                error_code: 1,
                msg: '用户名和密码不能为空！'
            })
            return
        }
        userModel.findOne({username}, (err, docs) => {
            if(err) {
                throw new Error(err)
            }
            if(!docs) {
                res.json({
                    error_code: 2,
                    msg: '用户名或密码错误！'
                })
                return
            }
            let bool = bcryptjs.compareSync(password, docs.password)
            console.log(bool, password);
            if(bool) {
                let token = jwt.sign({ 
                    username,
                    projectName: '2210diancan',
                    startTime: +new Date(),
                    expires: 7200 * 1000,
                 }, '2210diancan');
                res.json({
                    error_code: 0,
                    msg: '登录成功！',
                    data: {
                        token,
                        userid: docs._id,
                        username
                    }
                }) 
                return
            }
            res.json({
                error_code: 2,
                msg: '用户名或密码错误！'
            })
        })
    },
    userinfo(req, res) {
        let {userid} = req.params
        userModel.findOne({_id: userid}, (err, docs) => {
            if(err) {
                throw new Error(err)
            }
            res.json({
                error_code: 0,
                msg: '获取用户信息成功！',
                data: docs
            })
        })
    }
}